package com.controller;

import com.entity.Coupon;
import com.service.ICouponService;
import com.vo.adminVo.AddCouponVo;
import com.vo.couponVo.CouponListRequestVo;
import com.vo.couponVo.CouponListResponseVo;
import com.vo.couponVo.UpdateCouponVo;
import com.vo.productVo.addProductVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Describe 优惠券管理控制器
 */
@Controller
@RequestMapping("/coupon")
public class CouponController {
    @Resource
    ICouponService couponService;
    @Resource
    HttpServletRequest request;

    /**
     * 获取优惠券信息列表
     */
    @RequestMapping("/getCouponList")
    @ResponseBody
    public List<CouponListResponseVo> getCouponList(CouponListRequestVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            return couponService.getCouponList(vo);
        }
        return null;
    }

    /**
     * 修改优惠券信息
     */
    @RequestMapping("/updateCoupon")
    @ResponseBody
    public void updateCoupon(UpdateCouponVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            couponService.updateCoupon(vo);
        }
    }

    /**
     * 添加优惠券
     */
    @RequestMapping("/addCoupon")
    @ResponseBody
    public String addCoupon(AddCouponVo addVo, MultipartFile file) throws IOException {
        String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File dirs = new File("src/main/resources/static/images/coupon/"+filename);
        if (file.isEmpty()){
            couponService.addCoupon(addVo);
            return "图片上传失败！";
        }else {
            file.transferTo(new File(dirs.getAbsolutePath()));
            addVo.setImage("/static/images/coupon/"+filename);
            couponService.addCoupon(addVo);
            return "添加成功!";
        }
    }

    /**
     * 删除优惠券
     */
    @DeleteMapping("/deleteCoupon")
    @ResponseBody
    public void deleteCoupon(Integer[] id){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            couponService.deleteCoupon(id);
        }
    }
}
